package com.byq.ai.agentlab.service;

import com.byq.ai.agentlab.po.Conversation;
import jakarta.annotation.PostConstruct;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChatService {
    Map<String, Conversation> conversations = new HashMap<>();
    @Autowired ConversationService cservice;
    @PostConstruct
    public void init(){
        List<Conversation> cs = cservice.getAll();
        for(Conversation c :  cs){
            conversations.put(c.getId(), c);
        }


    }



    String systemMessage= """
            You are a doctor to help people keeping healthy. 
            A question is given which is enclosed by ```.
            Please give your response in chinese
            """;


    @Autowired
    ChatClient chatClient;
    public String  ask(String question,String cid){
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication p = ctx.getAuthentication();



        //
        Conversation con = conversations.get(cid);
        if(con == null){
            con = new Conversation(cid);
            conversations.put(cid, con);
            SystemMessage sm = new SystemMessage(systemMessage);
            con.getMessages().add(sm);
        }
        UserMessage um = new UserMessage(question);
        con.getMessages().add(um);

        List<Message> messages = con.getMessages();
        ChatClient.CallResponseSpec aws = chatClient.prompt().messages(messages)
                .call();

        String cont = aws.content();

        AssistantMessage am = new AssistantMessage(cont);


        con.getMessages().add(am);

        this.cservice.save(con);

        return cont;
    }


}
